<template>
  <div>
    <XmTable :config="tableConfig" :noWatchParams="noWatchParams" class="table" ref="table" @sort-change="handleSort">
      <div slot="filter">
        <el-form class="fl" :inline="true" ref="form" :model="noWatchParams">
          <el-form-item label="城市">
            <CitySelect class="w-100" ref="citySelect" v-model="noWatchParams.cityId" size="small" placeholder="城市" clearable filterable></CitySelect>
          </el-form-item>
          <el-form-item label="后台单号">
            <el-input v-model.trim="noWatchParams.xmbzNo" size="small" placeholder="后台单号" clearable></el-input>
          </el-form-item>
          <el-form-item label="平台单号">
            <el-input v-model.trim="noWatchParams.platformOrderId" size="small" placeholder="平台单号" clearable></el-input>
          </el-form-item>
          <el-form-item label="申请人">
            <el-input v-model.trim="noWatchParams.operator" size="small" placeholder="申请人" clearable></el-input>
          </el-form-item>
          <el-form-item label="处理人">
            <el-input v-model.trim="noWatchParams.personDispose" size="small" placeholder="申请人" clearable></el-input>
          </el-form-item>
          <el-form-item label="处理状态">
            <XmSelect v-model="noWatchParams.handleState" size="small" placeholder="处理状态" :options="stateList" clearable filterable></XmSelect>
          </el-form-item>
          <el-form-item label="工单来源">
            <XmSelect v-model="noWatchParams.source" size="small" placeholder="工单来源" :options="sourceTypeList" clearable filterable></XmSelect>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="startAndEndTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :default-time="['00:00:00', '23:59:59']"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions"
              size="small"
              align="right"
              clearable
              @change="handleTimeChange"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button plain type="primary" @click="search" size="small" icon="el-icon-search" style="margin-left: 10px;">查询
            </el-button>
            <el-button plain @click="reset" size="small" icon="el-icon-delete" style="margin-left: 10px;">重置</el-button>
            <el-button v-xmbz-permission="'classification_modifyOrder_add'" class="ml-20" plain icon="el-icon-plus" size="small" type="success" @click="add">添加</el-button>
            <el-button v-xmbz-permission="'classification_modifyOrder_batchAgree'" icon="el-icon-check" size="small" type="success" @click="batchAgree">一键同意</el-button>
          </el-form-item>
        </el-form>
      </div>

      <template slot="column-beforExtJson" slot-scope="{data}">
        <div>
          <div v-for="(field, i) in Object.keys(modifyFieldMap)" :key="i">
            <div v-if="data.beforExtJson[field] !== undefined">
              {{ modifyFieldMap[field] }}
              <span class="c-red fw-bold" v-if="field !== 'deliveryStartTime'">{{ data.beforExtJson[field] }}</span>
              <span class="c-red fw-bold" v-if="field === 'deliveryStartTime'">
                {{ `${data.beforExtJson.deliveryStartTime.slice(0, 10)} ${data.beforExtJson.deliveryStartTime.slice(10, 16)} - ${data.beforExtJson.deliveryEndTime.slice(10, 16)}` }}  
              </span>
            </div>
          </div>
        </div>
      </template>
      <template slot="column-extJson" slot-scope="{data}">
        <div>
          <div v-for="(field, i) in Object.keys(modifyFieldMap)" :key="i">
            <div v-if="data.extJson[field]">
              {{ modifyFieldMap[field] }}
              <span class="c-red fw-bold" v-if="field !== 'deliveryStartTime'">{{ data.extJson[field] }}</span>
              <span class="c-red fw-bold" v-if="field === 'deliveryStartTime'">
                {{ `${data.extJson.deliveryStartTime.slice(0, 10)} ${data.extJson.deliveryStartTime.slice(10, 16)} - ${data.extJson.deliveryEndTime.slice(10, 16)}` }}
              </span>
            </div>
          </div>
        </div>
      </template>
      <template slot="column-source" slot-scope="{data}">
        <span>{{ sourceMap[data.source] }}</span>
      </template>
      
      <template slot="column-handleState" slot-scope="{data}">
        <el-tag class="mr-5 mb-5" :type="stateMap[data.handleState].type" v-if="stateMap[data.handleState]">
          {{stateMap[data.handleState].label}}
        </el-tag>
      </template>
      <template slot="column-operate" slot-scope="{data}">
        <el-button v-xmbz-permission="'classification_modifyOrder_agree'" v-if="data.handleState == 1" type="success" class="ml-0 mr-5 mb-5" size="mini" @click="handleOrder(2, data)">
          同意
        </el-button>
        <el-button v-xmbz-permission="'classification_modifyOrder_reject'" v-if="data.handleState == 1" type="danger" class="ml-0 mr-5 mb-5" size="mini" @click="handleOrder(3, data)">
          拒绝
        </el-button>
        <el-button class="ml-0 mr-5 mb-5" size="mini" @click="viewLog(data)">
          日志
        </el-button>
      </template>
    </XmTable>

    <addDialog ref="addDialog" @submit="search"></addDialog>
    <orderLogDialog ref="orderLogDialog"></orderLogDialog>
  </div>
</template>

<script>
import { disposeOrder } from '@/api/workorder/modifyOrder'
import tableConfig from './config/table'
import addDialog from './addDialog'
import orderLogDialog from '@/components/dialog/orderLogDialog'

const modifyFieldMap = {
  receiverAddress: '地址：',
  mainWarehouse: '总仓：',
  branchWarehouse: '仓库：',
  deliveryStartTime: '配送时间：',
  productionNotes: '生产备注：',
  deliveryNotes: '配送备注：',
}

const stateMap = {
  1: {
    label: '未处理',
    type: 'info',
  },
  2: {
    label: '同意',
    type: 'success',
  },
  3: {
    label: '不同意',
    type: 'danger',
  },
}
const stateList = [{
  label: '未处理',
  value: '1',
},{
  label: '同意',
  value: '2',
},{
  label: '不同意',
  value: '3',
}]

const sourceTypeList = [{
  label: 'APP提交',
  value: '1',
},{
  label: '熊猫系统提交',
  value: '2',
}]
const sourceMap = {
  1: 'APP提交',
  2: '熊猫系统提交'
}

export default {
  data() {
    return {
      tableConfig,
      modifyFieldMap,
      stateMap,
      sourceMap,
      stateList,
      sourceTypeList,
      noWatchParams: {
        cityId: '',
        xmbzNo: '',
        platformOrderId: '',
        operator: '',
        personDispose: '',
        handleState: '1',
        source: '',
        timeStart: this.dayjs(new Date())
          .format("YYYY-MM-DD 00:00:00"),
        timeEnd: this.dayjs(new Date())
          .format("YYYY-MM-DD 23:59:59"),
        sort: '',
        order: '',
      },
      startAndEndTime: [this.dayjs(new Date())
        .format("YYYY-MM-DD 00:00:00"), this.dayjs(new Date())
        .format("YYYY-MM-DD 23:59:59")],
      pickerOptions:{
        onPick: (obj) => {
          this.pickerMinDate = new Date(obj.minDate).getTime();
        },
        disabledDate:(time)=> {
          if (this.pickerMinDate) {
            const day1 =  31 * 24 * 3600 * 1000;
            let maxTime = this.pickerMinDate + day1;
            let minTime = this.pickerMinDate - day1;
            return time.getTime() > maxTime || time.getTime()<minTime;
          }
        }
      },
      consultHappyServiceTypeList: []
    };
  },
  methods: {
    fetch() {
      this.$refs.table.fetch()
    },
    search() {
      this.fetch()
    },
    handleSort(column) {
      if (column && column.order) {
        if (column.order == 'descending') {
          this.noWatchParams.sort = `${column.prop}`
          this.noWatchParams.order = 'desc'
        } else {
          this.noWatchParams.sort = `${column.prop}`
          this.noWatchParams.order = 'asc'
        }
      } else {
        this.noWatchParams.sort = undefined
        this.noWatchParams.order = undefined
      }
      this.fetch()
    },
    reset() {
      this.startAndEndTime = [this.dayjs(new Date())
        .format("YYYY-MM-DD 00:00:00"), this.dayjs(new Date())
        .format("YYYY-MM-DD 23:59:59")]
      this.noWatchParams = {
        xmbzNo: '',
        platformOrderId: '',
        operator: '',
        personDispose: '',
        handleState: '1',
        source: '',
        timeStart: this.dayjs(new Date())
          .format("YYYY-MM-DD 00:00:00"),
        timeEnd: this.dayjs(new Date())
          .format("YYYY-MM-DD 23:59:59"),
        sort: '',
        order: '',
      }
      this.$nextTick(() => {
        this.fetch()
      })
    },
    add() {
      this.$refs.addDialog.show({ type: 'add' })
    },
    edit(data) {
      this.$refs.addDialog.show({ type: 'edit', data})
    },
    handleOrder(type, data) {
      const labelMap = {
        '2': '同意',
        '3': '拒绝',
      }
      const typeMap = {
        '2': 'success',
        '3': 'error',
      }
      this.$confirm(`确认是否${labelMap[type]}工单请求?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: typeMap[type],
      }).then(() => {
        disposeOrder([{
          id: data.id,
          handleState: type
        }]).then(res => {
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: '处理成功!'
            });
            this.fetch()
          } else {
            this.$message({
              type: 'error',
              message: res.data.msg
            });
          }
        })
      })
    },
    batchAgree() {
      const selectList = this.$refs.table.getSelection();
      if (selectList && selectList.length) {
        this.$confirm(`确认是否一键同意${selectList.length}条工单?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: 'success',
        }).then(() => {
          disposeOrder(selectList.map(item => {
            return {
              id: item.id,
              handleState: 2
            }
          })).then(res => {
            if (res.data.code === 200) {
              this.$message({
                type: 'success',
                message: '处理成功!'
              });
              this.fetch()
            } else {
              this.$message({
                type: 'error',
                message: res.data.msg
              });
            }
          })
        })
      } else {
        this.$message({
          message: '请勾选表格记录！',
          type: 'warning'
        })
      }
    },
    handleTimeChange() {
      this.noWatchParams.timeStart = this.startAndEndTime && this.startAndEndTime[0]
      this.noWatchParams.timeEnd = this.startAndEndTime && this.startAndEndTime[1]
    },
    viewLog(data) {
      this.$refs.orderLogDialog.show({orderId: data.orderId})
    },
  },
  created() {
  },
  components: {
    addDialog,
    orderLogDialog
  }
};
</script>
<style lang="scss" scoped>

</style>